package com.net.wanjian.networkhospitalmanager.activity.skilltrain;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.OperationImageGridAdapter;
import com.net.wanjian.networkhospitalmanager.bean.SearchDeviceDetailResult;
import com.net.wanjian.networkhospitalmanager.bean.StudentApplyReserveReturn;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.CompressPhotoUtil;
import com.net.wanjian.networkhospitalmanager.utils.PicassoUtil;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class SubmitLabActivity extends BaseActivity {
    public static final String LAB_RESERVE_MEMBER_OPERATION_KEY = "com.net.wanjian.activity.lab_reserve_member_operation_key";
    public static final String LAB_RESERVE_OPERATION_TYPE_KEY = "com.net.wanjian.activity.lab_reserve_operation_type_key"; //2是点击进来，1是扫描后进来

    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;

    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.top_title_tv)
    TextView topTitleTv;
    @BindView(R.id.submit_lab_device_iv)
    ImageView submitLabDeviceIv;
    @BindView(R.id.submit_lab_device_desc_tv)
    TextView submitLabDeviceDescTv;
    @BindView(R.id.submit_lab_device_sums_et)
    EditText submitLabDeviceSumsEt;
    @BindView(R.id.submit_lab_device_words_num_tv)
    TextView submitLabDeviceWordsNumTv;
    @BindView(R.id.submit_lab_device_btn_layout)
    RelativeLayout submitLabDeviceBtnLayout;
    @BindView(R.id.submit_lab_image_recycler)
    RecyclerView mImageRecyclerView;

    private ArrayList<String> imageUrls = new ArrayList<>();
    private OperationImageGridAdapter imageGridAdapter;
    private int poss;
    private LocalBroadcastManager localBroadcastManager;

    private SearchDeviceDetailResult.DataBean.LabReserveMemberOperationInfoBean infoBean;
    private int savePosition;

    @Override
    protected void initData() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        topBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageUrls.size() > 1 || !TextUtils.isEmpty(submitLabDeviceSumsEt.getText().toString().trim())) {
                    ProgressDialogUtils.showAskDialog(SubmitLabActivity.this, "", "放弃此次编辑并返回", "确定", "取消", new ProgressDialogUtils.OnClickDialogBtnListenner() {
                        @Override
                        public void onClickDialogBtn(int btnId) {
                            if (btnId == 1) {
                                SubmitLabActivity.this.finish();

                            }
                        }
                    }, true);
                } else {
                    SubmitLabActivity.this.finish();
                }
            }
        });
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            infoBean = (SearchDeviceDetailResult.DataBean.LabReserveMemberOperationInfoBean) bundle.getSerializable(LAB_RESERVE_MEMBER_OPERATION_KEY);
        }
        setUI();
    }

    //统一设置ui
    private void setUI() {
        topTitleTv.setText("设备");
//        topTitleTv.setText(URLDecoderUtil.getDecoder(infoBean.getDeviceName()));
        submitLabDeviceDescTv.setText(URLDecoderUtil.getDecoder(infoBean.getDeviceRemark()));
        submitLabDeviceSumsEt.setText(URLDecoderUtil.getDecoder(infoBean.getLabReserveMemberOperationRemark()));

        PicassoUtil.loadImage(this, HttpUtil.getDevicePhoto(URLDecoderUtil.getDecoder(infoBean.getDeviceID()), SharedXmlUtil.getInstance().getHospitalId()), R.mipmap.user, submitLabDeviceIv);

        //捕获edittext的文字个数
        submitLabDeviceSumsEt.addTextChangedListener(new TextWatcher() {
            private int selectionStart = 0;
            private int selectionEnd = 0;
            private CharSequence temp = null;

            public void afterTextChanged(Editable arg0) {

                selectionStart = submitLabDeviceSumsEt.getSelectionStart();
                selectionEnd = submitLabDeviceSumsEt.getSelectionEnd();

                if (temp.length() > 150) {
                    ToastUtil.showToast("文字字数超出限制");
                    arg0.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionStart;
                    submitLabDeviceSumsEt.setText(arg0);
                    submitLabDeviceSumsEt.setSelection(tempSelection);
                }

                submitLabDeviceWordsNumTv.setText("可输入" + (150 - arg0.length()) + "/150字");
            }

            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                temp = arg0;
            }

            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            }

        });

        //保存模型训练结果
        submitLabDeviceBtnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveDeviceOperationResult();
            }
        });

        //加载操作图片并显示
        mImageRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));

        if (imageUrls.size() == 0) {
            imageUrls.add("default");
        }

        imageGridAdapter = new OperationImageGridAdapter(this, imageUrls);
        mImageRecyclerView.setAdapter(imageGridAdapter);
        imageGridAdapter.setmOnItemClickListener(new OperationImageGridAdapter.OnItemClickListener() {
            @Override
            public void onPhotoClick(int position) {

                savePosition = position;
                if (imageUrls.get(position).equals("default") && imageGridAdapter.getItemCount() > 5) {
                    ToastUtil.showToast("最多上传5张图片，已达上限");
                    return;
                }

//                pickImage();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
                    requestPermission(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA});

                }

            }

            @Override
            public void onDelClick(int position) {
                imageUrls.remove(position);
                imageGridAdapter.notifyItemRemoved(position);
            }
        });
    }

    /*private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {

            if (savePosition == imageUrls.size() - 1) {
                //添加本地相册图片，更新视图
                MultiImageSelector.create()
                        .showCamera(true)// 是否显示相机. 默认为显示
                        .count(5) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() // 单选模式
                        .multi() // 多选模式, 默认模式;
//                            .origin() // 默认已选择图片. 只有在选择模式为多选时有效
                        .start(SubmitLabActivity.this, 10001);//添加
//                }

            } else {
                //修改图片，更新视图

                poss = savePosition;

                MultiImageSelector.create()
                        .showCamera(true)// 是否显示相机. 默认为显示
                        .count(5) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() // 单选模式
                        .multi() // 多选模式, 默认模式;
//                            .origin() // 默认已选择图片. 只有在选择模式为多选时有效
                        .start(SubmitLabActivity.this, 10002);//修改

            }

        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode){
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(SubmitLabActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        }else{
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }*/

    /**
     * 保存设备操作结果
     */
    private void saveDeviceOperationResult() {
        //获取实际选中的图片地址
        String[] imagePaths = new String[imageUrls.size() - 1];
        for (int i = 0; i < imageUrls.size() - 1; i++) {
            if (!imageUrls.get(i).equals("default")) {
                imagePaths[i] = imageUrls.get(i);
            }
        }

        List<String> strings = new ArrayList<>();
        for (int i = 0; i < imagePaths.length; i++) {
            strings.add(imagePaths[i]);
        }

        new CompressPhotoUtil().CompressPhoto(this, strings, new CompressPhotoUtil.CompressCallBack() {
            @Override
            public void success(List<String> list) {
                updown(list);
            }
        });


//        Log.e(TAG, "saveDeviceOperationResult: "+SharedXmlUtil.getInstance().getDeviceId()+"Token:"+SharedXmlUtil.getInstance().getToken()+
//                "医院ID"+SharedXmlUtil.getInstance().getHospitalId()+"数组"+imagePaths+"实验室预约人员操作ID"+infoBean.getLabReserveMemberOperationID()+
//                "心得体会"+submitLabDeviceSumsEt.getText().toString().trim()+"图片数量"+
//                imagePaths.length + "");


      /*  ProgressDialogUtils.showProgressDialog(this, null, R.string.upload_image);
        HttpUtil.saveDeviceOperationImageUpload(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                SharedXmlUtil.getInstance().getHospitalId(), imagePaths, infoBean.getLabReserveMemberOperationID(), submitLabDeviceSumsEt.getText().toString().trim(),
                imagePaths.length + "", new DisposableObserver<StudentApplyReserveReturn>() {
                    @Override
                    public void onNext(StudentApplyReserveReturn studentApplyReserveReturn) {
                        ProgressDialogUtils.dismissProgressDialog();
                        if (studentApplyReserveReturn.getResult().equals(ErrorCodeReturn.success + "")) {
                            ToastUtil.showToast("保存成功");
                            SubmitLabActivity.this.finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });*/
    }

    private void updown(List<String> list) {

        String[] imagePaths = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).equals("default")) {
                imagePaths[i] = list.get(i);
            }
        }


        ProgressDialogUtils.showProgressDialog(this, null, R.string.upload_image);
        HttpUtil.saveDeviceOperationImageUpload(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                SharedXmlUtil.getInstance().getHospitalId(), imagePaths, infoBean.getLabReserveMemberOperationID(), submitLabDeviceSumsEt.getText().toString().trim(),
                imagePaths.length + "", new DisposableObserver<StudentApplyReserveReturn>() {
                    @Override
                    public void onNext(StudentApplyReserveReturn studentApplyReserveReturn) {
                        ProgressDialogUtils.dismissProgressDialog();
                        if (studentApplyReserveReturn.getResult().equals(ErrorCodeReturn.success + "")) {
                            ToastUtil.showToast("保存成功");
                            SubmitLabActivity.this.finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null) {
            if (requestCode == 10001 || requestCode == 10002) {
                final ArrayList<String> paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                /*final ArrayList<String> paths = new ArrayList<>();
                List<Uri> uriList = Matisse.obtainResult(data);
                for (Uri uri:uriList) {
                    paths.add(uri+"");
                }*/
                //添加图片
                if (requestCode == 10001) {
                    //多个图片可以同时添加
                    if (paths.size() > 0) {
                        if (paths.size() == 1) {
                            //将添加的图片放在第一位
                            imageUrls.add(0, paths.get(0));
                            //更新第一个位置的图片
                            imageGridAdapter.notifyItemInserted(0);
                        } else {
                            if (imageUrls.size() + paths.size() > 6) {
                                ToastUtil.showToast("上传图片总数大于5张，无法添加");
                                return;
                            }
                            for (int i = 0; i < paths.size(); i++) {
                                imageUrls.add(i, paths.get(i));
                                Log.e(TAG, "onActivityResult: " + imageUrls.get(i));
                            }
                            imageGridAdapter.notifyDataSetChanged();
                        }

                    }

                }
                //修改图片
                else if (imageUrls.size() > 0) {
                    int pos = poss;
                    imageUrls.set(pos, paths.get(0));
                    imageGridAdapter.notifyItemChanged(pos);
                    imageGridAdapter.notifyDataSetChanged();
                }

            }
        }
    }

    @Override
    protected void onStop() {
        localBroadcastManager.sendBroadcast(new Intent(LaboratoryListActivity.LAB_RESERVE_BROAST_INTENT_REFRESH));
        super.onStop();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_submit_lab;
    }

    @Override
    protected void onRequestPermissionsResult(int requestCode, boolean isSuccess) {
        if (!isSuccess) {
            finish();
        } else {
            if (savePosition == imageUrls.size() - 1) {
                //添加本地相册图片，更新视图
                    MultiImageSelector.create()
                            .showCamera(true)// 是否显示相机. 默认为显示
                            .count(5) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                            .single() // 单选模式
                            .multi() // 多选模式, 默认模式;
//                            .origin() // 默认已选择图片. 只有在选择模式为多选时有效
                            .start(SubmitLabActivity.this, 10001);//添加
//                }

            } else {
                //修改图片，更新视图

                poss = savePosition;

                MultiImageSelector.create()
                        .showCamera(true)// 是否显示相机. 默认为显示
                        .count(5) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() // 单选模式
                        .multi() // 多选模式, 默认模式;
//                            .origin() // 默认已选择图片. 只有在选择模式为多选时有效
                        .start(SubmitLabActivity.this, 10002);//修改

            }
        }
    }

    @Override
    public void onBackPressed() {
        if (imageUrls.size() > 1 || !TextUtils.isEmpty(submitLabDeviceSumsEt.getText().toString().trim())) {
            ProgressDialogUtils.showAskDialog(SubmitLabActivity.this, "", "放弃此次编辑并返回", "确定", "取消", new ProgressDialogUtils.OnClickDialogBtnListenner() {
                @Override
                public void onClickDialogBtn(int btnId) {
                    if (btnId == 1) {
                        SubmitLabActivity.this.finish();

                    }
                }
            }, true);
        } else {
            super.onBackPressed();

        }
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

}
